#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM 5
int ticket = 300000;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mmtx = PTHREAD_MUTEX_INITIALIZER;
void *enter(void *args)
{
    while (true)
    {
        pthread_mutex_lock(&mtx);
        if (ticket <= 0)
        {
            pthread_cond_signal(&cond);
            pthread_mutex_unlock(&mtx);
            break;
        }
        pthread_cond_signal(&cond);
        ticket--;
        //sleep(1);
        cout << "我是线程：" << pthread_self() << endl
             << "还剩余数：" << ticket << endl;
        pthread_mutex_unlock(&mtx);
        pthread_mutex_lock(&mmtx);
        pthread_cond_wait(&cond, &mmtx);
        pthread_mutex_unlock(&mmtx);
    }
    // pthread_mutex_lock(&mmtx);
    // pthread_cond_wait(&cond, &mmtx);
    // pthread_mutex_unlock(&mmtx);
    return nullptr;
}
int main()
{
    pthread_t tid[NUM];
    for (int i = 0; i < NUM; i++)
    {
        pthread_create(tid + i, nullptr, enter, nullptr);
    }
    for (int i = 0; i < NUM; i++)
    {
        pthread_join(tid[i], nullptr);
    }
    cout << "回收资源成功" << endl;
    return 0;
}